import sys
sys.path.append('../face_recog/insightface/deploy')
sys.path.append('../face_recog/insightface/src/common')
from imutils import paths
import numpy as np
import argparse
import pickle
import cv2
import os
import time
from scipy import spatial

# similar_cost = 0.4

def findEulerDistance(vector1, vector2):
    """
    Calculate cosine distance between two vector
    """
    vec1 = vector1.flatten()
    vec2 = vector2.flatten()

    diff = np.subtract(vec1, vec2)
    dist = np.sqrt(np.sum(np.square(diff)))
    return dist

def CosineDistance(vector1,vector2):
    cos_dist = spatial.distance.cosine(vector1,vector2)
    return cos_dist

def one2one_embedding_compare(feature_data1, feature_data2):
    face_embedding1 = np.array(feature_data1, dtype=np.float32)
    face_embedding2 = np.array(feature_data2, dtype=np.float32)

    result = findEulerDistance(face_embedding1, face_embedding2)
    # result = CosineDistance(face_embedding1, face_embedding1)
    return result

def one2onne_embedding(user_id, user_embeddings, face_embedding):
    # convert face to RGB color
    t1 = time.time()
    # cv2.imwrite("test.jpg", frame)

    # print('bb2', time.time() - t1)
    # print(face_embedding is None)
    dist_lst = []
    ou_list = []
    for ebds in user_embeddings:
        ou_list.append(findEulerDistance(face_embedding,ebds))
        dist_lst.append(CosineDistance(face_embedding, ebds))
        # print('bb3', time.time() - t1)
    avg_dist = np.average(np.array(dist_lst))
    print(avg_dist)
    # print('bb4', time.time() - t1)
    if avg_dist < 0.4:
        # print('duideduie')
        return None, True, dist_lst, ou_list
    else:
        # print('bushiduide')
        return None, False, dist_lst, ou_list

###输入userid调embedding，输入图片计算embedding匹配，设定阈值
def one2onne(user_id,frame, user_embeddings, embedding_model):
    t1 = time.time()
    # cv2.imwrite("test.jpg", frame)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame = cv2.resize(frame, (112, 112))
    frame = np.transpose(frame, (2, 0, 1))
    # print('bb1', time.time() - t1)
    # Get the face embedding vector
    face_embedding = embedding_model.get_feature(frame)
    # print('bb2', time.time() - t1)
    # print(face_embedding is None)
    dist_lst = []
    ou_list = []
    for ebds in user_embeddings:
        ou_list.append(findEulerDistance(face_embedding,ebds))
        dist_lst.append(CosineDistance(face_embedding, ebds))
        # print('bb3', time.time() - t1)
    avg_dist = np.average(np.array(dist_lst))
    print(avg_dist)
    # print('bb4', time.time() - t1)
    if avg_dist < 0.4:
        # print('duideduie')
        return None, True, dist_lst, ou_list
    else:
        # print('bushiduide')
        return None, False, dist_lst, ou_list
    # else:
    #     raise ('搜索失败')
